package com.pug.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pug.product.bo.QuestionBO;
import com.pug.product.dto.QuestionTemplateQueryRespDTO;
import com.pug.product.mapper.QuestionTemplateMapper;
import com.pug.product.po.QuestionTemplatePO;
import com.pug.product.service.IQuestionTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author RenGaoshuai
 * @date 2023/8/7 10:25
 * @description
 */
@Service
public class QuestionTemplateServiceImpl implements IQuestionTemplateService {
    @Autowired
    private QuestionTemplateMapper questionTemplateMapper;

    @Override
    public QuestionTemplateQueryRespDTO selectById(Long id) {
        QuestionTemplatePO po = questionTemplateMapper.selectById(id);
        if (Objects.isNull(po)) {
            return null;
        }
        QuestionTemplateQueryRespDTO respDTO = BeanUtil.copyProperties(po, QuestionTemplateQueryRespDTO.class);

        List<QuestionBO> questionBOS = JSON.parseArray(po.getQuestionJson(), QuestionBO.class);
        respDTO.setQuestionList(questionBOS);
        return respDTO;
    }

    @Override
    public Integer calculateScore(String questionJson) {
        int totalScore = 0;
        JSONArray questions = JSONArray.parseArray(questionJson);
        if (Objects.isNull(questions)) {
            return totalScore;
        }
        for (int i = 0; i < questions.size(); i++) {
            JSONObject question = questions.getJSONObject(i);
            // 答案列表
            JSONArray options = question.getJSONArray("options");

            // 多选问题 取最大分数
            if (question.containsKey("multipleChoice")) {
                Integer highest = 0;
                for (int j = 0; j < options.size(); j++) {
                    JSONObject option = options.getJSONObject(j);
                    //check=true 是被选中的答案
                    if (option.getBoolean("check")) {
                        Integer score = option.getInteger("score");
                        highest += score;
                    }
                }

                Integer maxScore = Integer.valueOf(question.getString("maxScore"));
                totalScore += highest < maxScore ? highest : maxScore;

            }else{
                //单选
                for (int j = 0; j < options.size(); j++) {
                    JSONObject option = options.getJSONObject(j);
                    //check=true 是被选中的答案
                    if (option.getBoolean("check")) {
                        totalScore += option.getInteger("score");
                        break;
                    }
                }
            }
        }

        return totalScore;
    }
}
